package com.bdilab.iot.intercepter;

import com.alibaba.druid.util.StringUtils;
import com.bdilab.iot.consts.Constants;
import com.bdilab.iot.enums.HttpCodeEnum;
import com.bdilab.iot.model.User;
import com.bdilab.iot.service.UserService;
import com.bdilab.iot.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/8/1 10:39
 */
@Slf4j
public class JwtTokenFilter extends OncePerRequestFilter {

    private UserDetailsService userDetailsService;
    private TokenUtils tokenUtils;
    private UserService userService;

    public JwtTokenFilter(UserDetailsService userDetailsService, TokenUtils tokenUtils, UserService userService){
        this.userDetailsService = userDetailsService;
        this.tokenUtils = tokenUtils;
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader(Constants.TOKEN_HEADER_STRING);
        if ((!StringUtils.isEmpty(token)) && token.startsWith(Constants.TOKEN_PREFIX)) {
            String username = tokenUtils.getUsername(token);
            if(!StringUtils.isEmpty(username)){
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if(userDetails != null && SecurityContextHolder.getContext().getAuthentication() == null ){
                    if(tokenUtils.validateToken(token, new User(userDetails.getUsername(), userDetails.getPassword()))){
                        User user = userService.getUserByUserName(username);
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                                request));
                        logger.debug("authenticated user " + userDetails.getUsername() + ", setting security context");

                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        request.setAttribute(Constants.CURRENT_USER, user);
                    }
                }
            }
        }
        filterChain.doFilter(request, response);

    }


}
